package com.zbkj.service.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.constants.WeChatConstants;
import com.zbkj.common.model.wechat.WechatCallback;
import com.zbkj.service.dao.WechatCallbackDao;
import com.zbkj.service.service.WechatCallbackService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 微信小程序回调Service
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class WechatCallbackServiceImpl extends ServiceImpl<WechatCallbackDao, WechatCallback> implements WechatCallbackService {

    private static final Logger logger = LoggerFactory.getLogger(WechatCallbackServiceImpl.class);

    @Resource
    private WechatCallbackDao dao;

    /**
     * 微信回调
     * @param request request
     * @return String
     */
    @Override
    public String callback(String request) {
        System.out.println("微信小程序回调：" + request);
        JSONObject jsonObject = JSONObject.parseObject(request);
        System.out.println("微信小程序回调jsonObject：" + jsonObject);
        WechatCallback wechatCallback = new WechatCallback();
        wechatCallback.setToUserName(jsonObject.getString("ToUserName"));
        wechatCallback.setFromUserName(jsonObject.getString("FromUserName"));
        wechatCallback.setCreateTime(jsonObject.getLong("CreateTime"));
        wechatCallback.setMsgType(jsonObject.getString("MsgType"));
        wechatCallback.setEvent(jsonObject.getString("Event"));
        wechatCallback.setAddTime(DateUtil.date());
        wechatCallback.setContent(request);
        save(wechatCallback);
        switch (wechatCallback.getEvent()) {
        }
        return "success";
    }

    /**
     * 微信发货信息管理回调处理
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return String
     */
    @Override
    public String handleShippingCallback(HttpServletRequest request, HttpServletResponse response) {
        logger.info("处理微信发货信息管理回调");
        
        try {
            // 读取请求体内容
            StringBuilder requestBody = new StringBuilder();
            String line;
            try (BufferedReader reader = request.getReader()) {
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }
            }
            
            String requestContent = requestBody.toString();
            logger.info("微信发货信息管理回调内容: {}", requestContent);
            
            if (StrUtil.isBlank(requestContent)) {
                logger.warn("微信发货信息管理回调内容为空");
                return "success";
            }
            
            // 解析回调内容
            JSONObject callbackData = JSONObject.parseObject(requestContent);
            String event = callbackData.getString("Event");
            
            // 保存回调记录
            WechatCallback wechatCallback = new WechatCallback();
            wechatCallback.setToUserName(callbackData.getString("ToUserName"));
            wechatCallback.setFromUserName(callbackData.getString("FromUserName"));
            wechatCallback.setCreateTime(callbackData.getLong("CreateTime"));
            wechatCallback.setMsgType(callbackData.getString("MsgType"));
            wechatCallback.setEvent(event);
            wechatCallback.setContent(requestContent);
            wechatCallback.setAddTime(DateUtil.date());
            save(wechatCallback);
            
            // 处理不同的发货管理事件
            switch (event) {
                case WeChatConstants.WECHAT_CALLBACK_EVENT_TRADE_REMIND_ACCESS_API:
                    logger.info("接收到微信发货管理提醒接入API事件");
                    handleRemindAccessApi(callbackData);
                    break;
                case WeChatConstants.WECHAT_CALLBACK_EVENT_TRADE_REMIND_SHIPPING:
                    logger.info("接收到微信发货管理提醒上传发货信息事件");
                    handleRemindShipping(callbackData);
                    break;
                case WeChatConstants.WECHAT_CALLBACK_EVENT_TRADE_ORDER_SETTLEMENT:
                    logger.info("接收到微信发货管理订单结算事件");
                    handleOrderSettlement(callbackData);
                    break;
                default:
                    logger.info("未知的微信发货管理回调事件: {}", event);
                    break;
            }
            
            return "success";
            
        } catch (IOException e) {
            logger.error("读取微信发货信息管理回调请求失败", e);
            return "fail";
        } catch (Exception e) {
            logger.error("处理微信发货信息管理回调失败", e);
            return "fail";
        }
    }
    
    /**
     * 处理提醒接入API事件
     */
    private void handleRemindAccessApi(JSONObject callbackData) {
        logger.info("处理微信发货管理提醒接入API事件: {}", callbackData.toJSONString());
        // 这里可以添加具体的业务逻辑，比如发送通知给管理员
    }
    
    /**
     * 处理提醒上传发货信息事件
     */
    private void handleRemindShipping(JSONObject callbackData) {
        logger.info("处理微信发货管理提醒上传发货信息事件: {}", callbackData.toJSONString());
        // 这里可以添加具体的业务逻辑，比如自动触发发货信息上传
    }
    
    /**
     * 处理订单结算事件
     */
    private void handleOrderSettlement(JSONObject callbackData) {
        logger.info("处理微信发货管理订单结算事件: {}", callbackData.toJSONString());
        // 这里可以添加具体的业务逻辑，比如更新订单状态
    }
}

